#!/bin/sh

# Git prompt module for Clifm
# Dependencies: git, sed, cut, tr, uniq, tail
# Author: L. Abramovich
# License: GPL2+

# Usage:
# Edit your prompt (via 'prompt edit') and add this code:
#
# RegularPrompt="... ${m_git_prompt_status} ..."

cmd_output="$(git -c color.status=false status -sb 2>/dev/null)"

[ -z "$cmd_output" ] && exit 1

header="$(echo "$cmd_output" | sed -n 1p)"
files="$(echo "$cmd_output" | tail -n+2 | cut -c1-3 | uniq)"

case "$header" in
	*"/"*) tmp="$(echo "$header" | cut -d'/' -f2)" ;;
	*) tmp="$(echo "$header" | cut -d' ' -f2-10)" ;;
esac

branch="$(echo "$tmp" | cut -d' ' -f1)"

case "$tmp" in
	*"["*) ahead_behind="$(echo "$tmp" | cut -d' ' -f2-3 | tr -d '[]')" ;;
	*) ahead_behind="" ;;
esac

status=""

for i in $files; do
	case "$i" in
		".") status="${status}\e[36m+" ;;
		"D"*) status="${status}\e[31mD" ;;
		"M"*) status="${status}\e[32mM" ;;
		"R"*) status="${status}\e[35mR" ;;
		"U"*) status="${status}\e[33mU" ;;
		"A"*) status="${status}\e[32mA" ;;
		"??"*) status="${status}\e[31m?" ;;
    esac
done

branch_color="\e[22;35m"
sep_color="\e[2;37m"
end_color="\e[22;39m"

output="$branch_color$branch$sep_color|"

if [ -n "$ahead_behind" ]; then
	ab_color="\e[22;32m"
	[ "$(echo "$ahead_behind" | cut -b1)" != "a" ] && ab_color="\e[22;31m"
	output="$output$ab_color$ahead_behind$end_color"
else
	output="$output\e[22;32m=$end_color"
fi

[ -n "$status" ] && output="$output$sep_color|$end_color$status$end_color"

# FIXME: The POSIX version of echo does not support flags
echo -e "($output)"

exit 0
